﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using StoreManagement.Model;
using StoreManagement.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StoreManagement.ViewModel
{
    public class EditPasswordViewModel : ViewModelBase
    {
        private EditPasswordModel passwordModel = new EditPasswordModel();
        public EditPasswordModel PasswordModel
        {
            get { return passwordModel; }
            set { passwordModel = value; RaisePropertyChanged(); }
        }

        //修改密码
        public RelayCommand<Window> EditPasswordCommand
        {
            get
            {
                var command = new RelayCommand<Window>((window) =>
                {
                    if (string.IsNullOrEmpty(PasswordModel.OldPassword) == true
                    || string.IsNullOrEmpty(PasswordModel.NewPassword) == true
                    || string.IsNullOrEmpty(PasswordModel.Password2) == true)
                    {
                        MessageBox.Show("不能为空");
                        return;
                    }

                    if (AppData.Instance.User.Password != PasswordModel.OldPassword)
                    {
                        MessageBox.Show("旧密码错误");
                        return;
                    }

                    if (PasswordModel.NewPassword != PasswordModel.Password2)
                    {
                        MessageBox.Show("两次新密码不一致");
                        return;
                    }

                    var user = AppData.Instance.User;
                    user.Password = passwordModel.NewPassword;

                    UserInfoService userInfoService = new UserInfoService();
                    int count = userInfoService.Update(user);
                    if (count > 0)
                    {
                        MessageBox.Show("修改成功");
                        window.Close();
                    }
                    else
                    {
                        MessageBox.Show("修改失败");
                    }
                });

                return command;
            }
        }
    }
}
